// 云函数入口文件
const cloud = require('wx-server-sdk')
const tencentcloud=require('tencentcloud-sdk-nodejs-aiart');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const secret_id="AKIDTrAyiFbZZQ7cx77znSyQflz6B6sUxEID";
const secret_key="mMjwwjKixzqUyIHAsX3PZZO2XtAKRN6i";
const clothesfilemapping={
  'test1':'cloud://cloud1-7gzzos73c6bd9439.636c-cloud1-7gzzos73c6bd9439-1380963984/user_img/1.jpg',
}
const aiart_client = tencentcloud.aiart.v20221229.Client;
const client = new aiart_client({
  credential: {
    secretId: secret_id,
    secretKey: secret_key,
  },
  region: "ap-guangzhou", 
  profile: {
    httpProfile: {
      endpoint: "aiart.tencentcloudapi.com",
    },
  },
});
// 云函数入口函数
exports.main = async (event, context) => {
  console.log('后端收到的 event:', event);
  try{
  // 支持前端传入的字段名：selfieFileID 和 productFileID（单张商品图）
  const { selfieFileID, productFileID, clothesType } = event || {}
  if (!selfieFileID || !productFileID) {
    throw new Error('缺少 selfieFileID 或 productFileID')
  }
    const result=await cloud.getTempFileURL({
      fileList:[selfieFileID, productFileID],
    });
    const user_URL=result.fileList[0].tempFileURL;
    const selected_URL=result.fileList[1].tempFileURL;
    console.log(user_URL);
    console.log(selected_URL);
    console.log("调用中");
    // const user_promise = cloud.downloadFile({ fileID: user_id });
    // const selected_promise = cloud.downloadFile({ fileID:selected_img_cloudid });
    // const [user_res, selected_res] = await Promise.all([user_promise, selected_promise]);
    // const user_buffer = user_res.fileContent;
    // const selected_buffer = selected_res.fileContent;
    // const user_base = user_buffer.toString('base64');
    // const selected_base = selected_buffer.toString('base64');
    // console.log('Base64 转换完成');这个api不支持传base64的二进制文件，这边这个尝试放弃
  const params={
    "ModelUrl":user_URL,
    "ClothesUrl":selected_URL,
    "ClothesType": clothesType || 'Upper-body'
  }
  const response = await client.ChangeClothes(params);
  const result_base=response.ResultImage;
  const result_buffer =Buffer.from(result_base,'base64');
  const cloud_path=`result_img/${Date.now()}.png`;
  const upload=await cloud.uploadFile({
    cloudPath:cloud_path,
    fileContent:result_buffer,
  })
  console.log('已存,FileID:',upload);
  return {
    success:true,
    result_file_id:upload.fileID,
  };}
  catch(error){
    console.error('执行出错');
    return {success:false,error:error.message};
  }
}
